package run.vue.iblog.controller;

import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import run.vue.iblog.common.Result;
import run.vue.iblog.common.ResultFactory;
import run.vue.iblog.dto.PartUserDto;
import run.vue.iblog.dto.PasswordsDto;
import run.vue.iblog.entity.User;
import run.vue.iblog.service.UserService;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author anonymous
 * @since 2020-06-14
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    // 根据用户名获取用户信息
    @GetMapping("/userinfo/{username}")
    public Result getByUsername(@PathVariable(name = "username") String username){
        System.out.println(username);
        User user = userService.getByUsername(username);

        // 获取部分信息
        PartUserDto partUserDto = new PartUserDto();
        partUserDto.setUserId(user.getId());
        partUserDto.setUsername(user.getUsername());
        partUserDto.setAvatar(user.getAvatar());
        partUserDto.setEmail(user.getEmail());
        partUserDto.setLastLogin(user.getLastLogin());
        partUserDto.setRealname(user.getRealname());
        partUserDto.setTelephone(user.getTelephone());

        return ResultFactory.success("获取信息成功",partUserDto);
    }


    @RequiresAuthentication //登录权限验证:即登录之后才可以访问该接口
    @GetMapping("/index")
    public Object index(){
        User user = userService.getById(1L);
        return ResultFactory.success(user);
    }

    @GetMapping("/error")
    public Object error(){
        return ResultFactory.error("操作失败");
    }


    @PutMapping("/save")
    public Result save(@Validated @RequestBody User user){
        userService.updateInfo(user);

        return ResultFactory.success("更新成功");
    }


    @PutMapping("/password")
    public Result changePassword(@RequestBody PasswordsDto passwordsDto){
        System.out.println(passwordsDto);
        userService.updatePassword(passwordsDto);
        return ResultFactory.success("修改成功");
    }

}
